Safe C++ by Vladimir Kushnir

Safe C++ by Vladimir Kushnir

Author:Vladimir Kushnir [Vladimir Kushnir]
Language: eng
Format: epub
Tags: COMPUTERS / Programming Languages / C++
ISBN: 9781449321352
Publisher: O'Reilly Media
Published: 2012-05-29T16:00:00+00:00


Provide both methods.

There is also an opposite situation when the SomeClass::Find() method returns a pointer to an object but the user does not have ownership of it:

// Returns a pointer to a result, caller DOES NOT OWN the result. MyClass* SomeClass::Find(const Inputs& inputs);

In this case, the pointer returned by this function points to an object that belongs to something inside the SomeClass object.

The first problem here is that the SomeClass object thinks that it is responsible for deleting the MyClass instance to which it just returned a pointer, and therefore it will delete it at some point in the future. In this case, if the user of this function will delete the pointer he received, this instance will be deleted more than once, which is not a good idea. Second, this instance might be part of an array of MyClass objects that is created inside, say, a template vector using operator new[] (with brackets), and we are now trying to delete an object from that array using operator delete without brackets. This is also not good. Finally, the instance of MyClass could be created on stack, and should not ever be deleted using operator delete at all.

In this case, any attempt to delete this object that we do not own—directly or by assigning it to a smart pointer of any kind that would take ownership of it—would lead to disaster. An appropriate way of returning this pointer is to return a “semi-smart” pointer that does not own the object it points to. This will be discussed in the next chapter.

Rules for this chapter to avoid memory leaks:

Every time you create an object using the new operator, immediately assign the result to a smart pointer (reference counting point or scoped pointer is recommended).



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.